<template>
  <div class="home" :style="bgStyle">
    <van-row style="width: 100%; height: 500px;">
      <van-button type="primary" @click="startAnwer">开始答题</van-button>
    </van-row>
    <van-row>
      <div style="width: 100%; min-height: 800px; height: 100%; margin-bottom: 20px;">
        <van-cell-group inset>
          <van-cell title="活动说明" />
          <!--奖品列表-->
            <van-list>
              <van-cell title="活动奖品" ></van-cell>
                <van-card v-for="item in taskInfo.awards"
                  :desc="item.awardName"
                  :title="item.awardsLevel"
                  thumb="https://fastly.jsdelivr.net/npm/@vant/assets/ipad.jpeg"
                  :num="item.awardNums"
                  
                />
               
            </van-list>
            <!--活动相关信息-->
            <van-list>
              <van-cell title="活动时间" :label="`${taskInfo.startTime}-${taskInfo.endTime}`" />
              <van-cell title="主办单位" :label="taskInfo.organizer" />
              <van-cell title="活动规则" :label="`达到${taskInfo.awardsPoints}分可有抽奖机会`" />
              <van-cell title="活动说明" :label="taskInfo.memo" />
              <van-cell title="我的联系方式" is-link to="/contact-info" />
              <van-cell title="获奖信息" to="/awardsList" is-link  />
            </van-list>
        </van-cell-group>
        
      </div>
    </van-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import HelloWorld from '@/components/HelloWorld.vue'; // @ is an alias to /src
import { useRoute, useRouter } from 'vue-router';
import { getInfo,getJssdkConfig } from '../api/base.js';
import { getTask, getAppSetting, getQuestion } from '../api/task.js';
import { wxLogin } from '../api/user';
import { showNotify } from 'vant'
import wx from "weixin-js-sdk";

const route = useRoute();
const router = useRouter();

const taskId = route.params.id;
localStorage.setItem('taskId', taskId)

const nowAppSetting = ref({});
const initAppSetting = ref({
  "home": {
    "bgStyle": {
      "backgroundColor": "#fff",
      "backgroundRepeat": "no-repeat",
      "backgroundSize": "contain"
      // "backgroundImage": "url(https://s3.cn-north-1.jdcloud-oss.com/fkhd/微信截图_20230111155108_20231115094130A001.png)"
    }
  },
  "activeProcess": {},
  "answerAnalysis": {},
  "successfulChallenge": {},
  "shareEffect": {}
});

const taskInfo = ref({
  startTime: "",
  endTime: "",
  awards: [],
  organizer: "",
  memo: "",
  awardsPoints: '',  
})

const bgStyle = computed(() => {
  let tempBgStyle = initAppSetting.value.home.bgStyle;
  if (nowAppSetting.value.home && nowAppSetting.value.home.bgStyle) {
    tempBgStyle = {...tempBgStyle, ...nowAppSetting.value.home.bgStyle}
  }
  return tempBgStyle;
})

onMounted(() => {
  // login();
  getAppSettings();
  getTaskInfo();
})

function getAppSettings() {
  getAppSetting({taskId}).then(res => {
    console.log(res, 'res - getAppSetting');
    if (res.code == 200) {
      nowAppSetting.value = res.data;
    }        
  })
}

// 获取任务信息
function getTaskInfo(){
  getTask(taskId).then(res=>{
    console.log(res)
    taskInfo.value = res.data;
  })
}

function startAnwer() {
  const data = {
    taskId
  };
  data.latitude = localStorage.getItem('latitude');
  data.longitude = localStorage.getItem('longitude');
  data.memberId = localStorage.getItem('token');
  data.preview = true;
  getQuestion(data).then(res=>{
    console.log(res, 'res');
    if (res.code == 200) {
      router.replace(`/answer/${taskId}`)
    } else {
      showNotify({ message: res.msg, type: 'danger' })
    }
  })
}

function login() {
  if (sessionStorage.getItem('noToken') == 'noToken') {
    return false;
  }

  // 确保每次都刷新 token 
  const token = sessionStorage.getItem('token');
  if (!token) {
    const code = route.query.code;
    if (code) {
      console.log(1);
      wxLogin(code).then((res) => {
        console.log(res, 'res');

        sessionStorage.setItem('token', res.openid)
        localStorage.setItem('token', res.openid)
        localStorage.setItem('avatar', res.headimgurl)

        // const fullPath = localStorage.getItem('fullPath');
        // console.log(fullPath, 'fullPath');

        getWxConfig()

        // if (fullPath) {
        //   location.href = fullPath
        // } else {
        //   location.href = '/'
        // }
      })
    } else {
      console.log('重定向授权');

      const appid = process.env.VUE_APP_WX_APPID;
      const redirect_uri = location.href;
      const redirect_url = encodeURIComponent(redirect_uri);
      const scope = "snsapi_userinfo"; // snsapi_userinfo || snsapi_base
      let state = ''
      state = encodeURIComponent(state);
      var url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_url}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`
      window.location.href = url
    }
  }
}

function getWxConfig() {
  // 获取微信配置
  const url = location.href.split('#')[0];
  console.log('url',url);
  getJssdkConfig(url).then(res=>{
    console.log('getwxconfig',res)
    wx.config({
      debug: false,
      appId: res.data.appId,
      timestamp: res.data.timestamp,
      nonceStr: res.data.nonceStr,
      signature: res.data.signature,
      jsApiList: ['getLocation', 'updateAppMessageShareData'] // 必填，需要使用的JS接口列表
    });
    wx.error(function(res){
      console.log('error',res)
    }) 
    wx.ready(()=>{
      console.log('ready',wx)
      // 获取地理位置
      wx.getLocation({
        type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
        success: function (res) {
          console.log('getLocation',res)
          const latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
          const longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
          const speed = res.speed; // 速度，以米/每秒计
          const accuracy = res.accuracy; // 位置精度
          localStorage.setItem('latitude',latitude)
          localStorage.setItem('longitude',longitude)
        }
      })

      getAppSetting({taskId}).then(res => {
        if (res.code == 200) {
          console.log(res.data, 'getAppSetting res.data');
          if (res.data.shareEffect && res.data.shareEffect.share) {
            const shareObj = res.data.shareEffect.share;
            wx.updateAppMessageShareData({
              title: shareObj.title, // 分享标题
              desc: shareObj.content, // 分享描述
              link: url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl: shareObj.icon, // 分享图标
              success: function () {
                // 设置成功
              }
            })
          }
        }
      })
    })
  })
}

</script>
<style lang="less">
.home {
  width: 100%;
  height: auto;
  min-height: 750px;
  background: url(../assets/images/mainbg.jpg) no-repeat;
  overflow-y: auto;
  .van-row .van-button {
    margin: 10rem auto;
    width: 200px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    border-radius: 25px;
    background: #2b3fc5;
    color: #fff;
  }
}
</style>
